package redis.work;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.model.User;
import redis.util.JedisPoolFactory;

/**
 * @author houweitao
 * @date 2016年5月16日下午4:34:40
 * @end 今日可关注人数已达上限，请明天再关注 2016年05月16日17:47:29
 */

public class AddFollow {

	private static final Logger log = LoggerFactory.getLogger(AddFollow.class);
	private JedisPool pool;
	private int threadCount = 20;
	private boolean killThread = false;
	public int count = 0; // 表示有多少个线程处于wait状态
	private String toFollow = "HUPU$PEOPLE2FOLLOW";
	private String alreadyFollow = "HUPU$ALREADYFOLLOW";
	private Map<String, String> cookies;

	public static void main(String[] args) {
		AddFollow af = new AddFollow();
		af.init();
		// af.deleteRedis();
	}

	private void deleteRedis() {
		pool = new JedisPoolFactory().getInstance();
		Jedis jedis = pool.getResource();
		System.out.println(jedis.del(toFollow));
		System.out.println(jedis.del(alreadyFollow));
	}

	@SuppressWarnings("deprecation")
	public void init() {
		cookies = getHupuCookies(
				"_cnzz_CV30020080=buzi_cookie%7C49d7897e.3443.76e3.0b4a.000b1a81d811%7C-1; _dacevid3=49d7897e.3443.76e3.0b4a.000b1a81d811; _HUPUSSOID=3dab5437-5a6e-4533-9702-dd6f060c1663; __gads=ID=f8d8bba74287bab9:T=1455692568:S=ALNI_MbLOMDpCv_sw35rugMZbBBK-0WKrw; AUM=dguB2Yw1io5CSAPLc7pWUrnHjN5nt-yqlWtWpTno5j7lw; vjuids=5d2e0f145.153c201038f.0.b16cf7db; vjlast=1459248760.1459248760.30; CNZZDATA30020080=cnzz_eid%3D952566052-1459239898-http%253A%252F%252Fnba.hupu.com%252F%26ntime%3D1459269436; __dacevid3=0xfd1f3600961a7ec7; Hm_lvt_c001b67f70039d825f661bc9fc3a0ac4=1462720558; __utma=1.49388104.1462934507.1462934507.1462934507.1; __utmz=1.1462934507.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=k87mt9594je7rfe65u1kfv2f92; _CLT=918ebe7bb324d8673460f7af1d701a5c; u=15710270|5YWz5rOo6L6+5Lq6|afe8|9858b86dda9b4d71eb24aaeb47b71bce|da9b4d71eb24aaeb|5YWz5rOo6L6+5Lq6; ua=20611088; __dacevst=9a507bc2.efc11c1d|1463389910643; _cnzz_CV30020080=buzi_cookie%7C49d7897e.3443.76e3.0b4a.000b1a81d811%7C-1");

		pool = new JedisPoolFactory().getInstance();
		Jedis jedis = pool.getResource();
		System.out.println(jedis.del(toFollow));
		System.out.println(jedis.del(alreadyFollow));
		jedis.rpush(toFollow, "http://my.hupu.com/mjlwm23");
		System.out.println("当前：" + jedis.llen(toFollow));
		pool.returnResource(jedis);
		begin();
	}

	private void begin() {
		for (int i = 0; i < threadCount; i++) {
			new Thread(new Runnable() {
				Jedis jedis = pool.getResource();

				@SuppressWarnings("deprecation")
				public void run() {
					log.info("run: " + Thread.currentThread().getName());
					while (!killThread) {
						try {
							log.info("当前进入" + Thread.currentThread().getName());
							log.info("待爬取链接数量：" + jedis.llen(toFollow));
							log.info("已关注数量：" + jedis.hlen(alreadyFollow));
							if (jedis.llen(toFollow) == 0) {
								killThread = true;
								log.info(Thread.currentThread().getName() + " 爬取队列为空！！break！！");
								break;
							}

							String url = jedis.lpop(toFollow);
							if (url != null && url.length() != 0) {
								try {
									follow(url, jedis);
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else {

							}
						} catch (Exception e) {
							pool.returnBrokenResource(jedis);
							jedis = pool.getResource();
						}
					}
					log.info("end: " + Thread.currentThread().getName());
					pool.returnResource(jedis);
				}

			}, "thread-" + i).start();

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

	private void follow(String url, Jedis jedis) {
		try {
			Document doc = Jsoup.connect(url).followRedirects(true).timeout(10000)
					.userAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)").cookies(cookies).get();
			Elements people = doc.select("#sidebar").select("li").select("a.u").select("a[href]");

			for (Element e : people) {
				String newUrl = e.attr("abs:href");
				System.out.println(newUrl);
				if (!jedis.hexists(alreadyFollow, newUrl)) {
					jedis.hset(alreadyFollow, newUrl, "1");
					jedis.rpush(toFollow, newUrl);

					if (notFollow(newUrl)) {
						Document helpId = Jsoup.connect(newUrl + "/profile").followRedirects(true).timeout(10000)
								.userAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)").cookies(cookies).get();
						String id = helpId.select(".profile_table").select("tr").first().text().split("：")[1].trim();

						Map<String, String> params = new HashMap<String, String>();
						params.put("u", id);
						params.put("t", "follow");
						Document fol = Jsoup.connect("http://my.hupu.com/ajax/buddys.ajax.php").followRedirects(true)
								.timeout(10000)
								.userAgent(
										"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
								.cookies(cookies).data(params).post();
						if (fol.text().equals("关注成功"))
							log.info("关注成功: " + newUrl);
						else
							log.info("关注失败: " + newUrl);
					}
				} else {
					log.info("之前已经关注");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private boolean notFollow(String url) {
		try {
			Document doc = Jsoup.connect(url).followRedirects(true).timeout(10000)
					.userAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)").cookies(cookies).get();

			String flag = doc.select("div#act.ga").text();
			if (flag != null && flag.contains("已关注"))
				return false;
			else if (flag != null && flag.contains("关注此人"))
				return true;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public Map<String, String> getHupuCookies(String str) {
		Map<String, String> map = new HashMap<>();

		String[] strs = str.split(";");
		for (String s : strs) {
			System.out.println(s.trim());
			String[] toAdd = s.trim().split("=");
			map.put(toAdd[0], toAdd[1]);
		}

		// ctrl+shift+j，然后输入document.cookie回车
		return map;
	}

}
